<template>
  <div class="layout-container">
    <div class="layout-container-form flex space-between">
      <div class="layout-container-form-handle">
        <el-button type="primary" :icon="Plus" v-permission="['超级管理员', '总经理']" @click="handleAdd">{{
          $t("message.common.add")
        }}</el-button>
        <el-popconfirm :title="$t('message.common.delTip')" @confirm="handleDel(chooseData)">
          <template #reference>
            <el-button type="danger" :icon="Delete" v-permission="['超级管理员']" :disabled="chooseData.length === 0">{{
          $t("message.common.delBat")
        }}</el-button>
          </template>
        </el-popconfirm>
      </div>
      <div class="layout-container-form-search">
        <el-input v-model="query.keyWord" clearable :placeholder="$t('message.common.searchTip')"></el-input>
        <el-button type="primary" :icon="Search" class="search-btn" @click="getTableData(true)">{{
          $t("message.common.search") }}</el-button>
      </div>
    </div>
    <div class="layout-container-table">
      <Table ref="table" v-model:page="page" v-loading="loading" :showSelection="true" :data="tableData"
        @getTableData="getTableData" @selection-change="handleSelectionChange">
        <el-table-column prop="userName" label="账号" align="center" />
        <el-table-column prop="userTrueName" label="姓名" align="center" />
        <el-table-column prop="departmentName" label="部门" align="center" />
        <el-table-column prop="roleName" label="角色" align="center" />
        <el-table-column prop="gender" label="性别" align="center">
          <template #default="scope">
            <span class="statusName">{{ scope.row.gender === 1 ? "男" : "女" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="tel" label="电话" align="center" />
        <el-table-column prop="email" label="邮箱" align="center" />
        <el-table-column prop="birthDate" label="出生日期" align="center">
          <template #default="scope">
            {{ convertDate(scope.row.birthDate) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('message.common.handle')" align="center" fixed="right" width="200">
          <template #default="scope">
            <el-button @click="handleEdit(scope.row)">{{
          $t("message.common.update")
        }}</el-button>
            <el-popconfirm :title="$t('message.common.delTip')" @confirm="handleDel([scope.row])">
              <template #reference>
                <el-button type="danger" v-permission="['超级管理员']">{{ $t("message.common.del") }}</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </Table>
      <Layer :layer="layer" @getTableData="getTableData" v-if="layer.show" />
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed, ref, reactive } from "vue";
import { Page } from "@/components/table/type";
import { getData, del } from "@/api/system/user";
import { roleData, departmentData } from './enum'
import { LayerInterface } from "@/components/layer/index.vue";
import { ElMessage } from "element-plus";
import Table from "@/components/table/index.vue";
import Layer from "./layer.vue";
import { Plus, Delete, Search } from '@element-plus/icons'
import { number } from "echarts";
import Permission from '@/directive/permission'
export default defineComponent({
  name: 'crudTable',
  components: {
    Table,
    Layer
  },
  directives: {
    Permission
  },
  setup() {
    // 计算属性基本使用
    const convertDate = computed(() => (date: Date) => {
      if (!date) return ''
      var date = new Date(date);
      return [date.getFullYear(), date.getMonth() + 1, date.getDate()].join('-')
    })
    // 存储搜索用的数据
    const query = reactive({
      keyWord: "",
    });
    // 弹窗控制器
    const layer: LayerInterface = reactive({
      show: false,
      title: "新增",
      showButton: true,
    });
    // 分页参数, 供table使用
    const page: Page = reactive({
      index: 1,
      size: 20,
      total: 0,
    });
    const loading = ref(true);
    const tableData = ref([]);
    const chooseData = ref([]);
    const handleSelectionChange = (val: []) => {
      chooseData.value = val;
    };
    // 获取表格数据
    // params <init> Boolean ，默认为false，用于判断是否需要初始化分页
    const getTableData = (init: Boolean) => {
      loading.value = true
      if (init) {
        page.index = 1
      }
      let params = {
        pageIndex: page.index,
        pageSize: page.size,
        ...query
      }
      getData(params)
        .then((res) => {
          let data = res.data.list
          if (Array.isArray(data)) {
            data.forEach(d => {
              const role = roleData.find(r => r.value === d.role_Id)
              role ? d.roleName = role.label : d.role_Id
              const department = departmentData.find(o => o.value === d.department_Id)
              department ? d.departmentName = department.label : d.department_Id
            })
          }
          data.forEach((d: any) => {
            d.loading = false
          })
          tableData.value = data
          page.total = res.data.total.value
        })
        .catch((error) => {
          tableData.value = [];
          page.index = 1;
          page.total = 0;
        })
        .finally(() => {
          loading.value = false;
        });
    }
    // 删除功能
    const handleDel = (data: object[]) => {
      let params = {
        ids: data
          .map((e: any) => {
            return e.user_Id;
          }),
      };

      del(params.ids).then((res) => {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        getTableData(tableData.value.length === 1 ? true : false);
      });
    }
    // 新增弹窗功能
    const handleAdd = () => {
      layer.title = "新增数据";
      layer.show = true;
      delete layer.row;
    }
    // 编辑弹窗功能
    const handleEdit = (row: any) => {
      layer.title = "编辑数据";
      layer.row = row;
      layer.show = true;
    }
    getTableData(true)
    return {
      Plus,
      Delete,
      Search,
      query,
      tableData,
      chooseData,
      roleData,
      departmentData,
      loading,
      page,
      layer,
      handleSelectionChange,
      getTableData,
      handleDel,
      handleAdd,
      handleEdit,
      convertDate
    };
  }
});
</script>

<style lang="scss" scoped>
.statusName {
  margin-right: 10px;
}
</style>
